/** biome-ignore-all lint/suspicious/noExplicitAny: off */
import type { Middleware } from '../context/types';

// 数据转换中间件，用于深拷贝数据
export const deepCloneMiddleware: Middleware = (_key, value, next) => {
  // 深拷贝函数
  const deepClone = <T>(obj: T): T => {
    if (obj === null || typeof obj !== 'object') {
      return obj;
    }

    if (obj instanceof Date) {
      return new Date(obj.getTime()) as unknown as T;
    }

    if (Array.isArray(obj)) {
      return obj.map((item) => deepClone(item)) as unknown as T;
    }

    if (typeof obj === 'object') {
      const clonedObj = {} as T;
      for (const prop in obj) {
        if (Object.hasOwn(obj, prop)) {
          clonedObj[prop] = deepClone(obj[prop] as any);
        }
      }
      return clonedObj;
    }

    return obj;
  };

  // 深拷贝值，避免直接修改原始数据
  const clonedValue = deepClone(value);
  next(clonedValue);
};

// 数据转换中间件，用于冻结对象
export const freezeMiddleware: Middleware = (_key, value, next) => {
  // 只冻结对象类型
  if (value !== null && typeof value === 'object') {
    const frozenValue = Object.freeze(value);
    next(frozenValue);
  } else {
    next(value);
  }
};

// 数据转换中间件，用于确保值不为空
export const nonNullableMiddleware: Middleware = (key, value, next) => {
  const finalValue = (value ?? key.includes('count')) ? 0 : '';
  next(finalValue);
};

// 数据转换中间件，用于将值转换为指定类型
export const typeTransformMiddleware: Middleware = (key, value, next) => {
  // 根据key后缀转换类型
  if (key.endsWith('_number')) {
    next(Number(value));
  } else if (key.endsWith('_boolean')) {
    next(Boolean(value));
  } else if (key.endsWith('_string')) {
    next(String(value));
  } else if (key.endsWith('_array')) {
    next(Array.isArray(value) ? value : [value]);
  } else {
    next(value);
  }
};
